package com.ibix.netty.communion;

import com.ibix.constant.OtherInfo;
import com.ibix.gui.GuiStructure;
import com.ibix.gui.component.MainFrame;
import com.ibix.gui.component.MessageFrame;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import javax.swing.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;

/**
 * Created by Administrator on 2018/1/23.
 */
public class MyClient  {
    private static Bootstrap bootstrap;
    private static ChannelFutureListener channelFutureListener = null;
    private static MessageFrame messageFrame;

    public MyClient(){}

    public void start() throws InterruptedException,IOException {
        EventLoopGroup group = new NioEventLoopGroup();
        try{
            bootstrap = new Bootstrap();
            bootstrap.group(group);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.handler(new MyClientInitializer());
            Channel channel = bootstrap.connect(OtherInfo.SERVER_HOST, OtherInfo.SERVER_PORT).sync().channel();
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            messageFrame = new MessageFrame("与服务器连接已断开正重新连接...");
            channelFutureListener = new MyChannelFutureListener(messageFrame);
            while(true){
                String line = in.readLine();
                if(line == null){
                    continue;
                }
            }
        }finally {
            group.shutdownGracefully();
            Object[] options = {"确定"};
            JOptionPane.showOptionDialog(GuiStructure.getMainFrame(),"初始化网络连接时出错，请检查本地网络配置","提示",JOptionPane.DEFAULT_OPTION,JOptionPane.ERROR_MESSAGE,null,options,options[0]);
            System.exit(0);
        }
    }

    public static void doConnect(){
        System.out.println("开始重新连接");
        if(!messageFrame.isVisible())
        {
            messageFrame.setVisible(true);
        }
        ChannelFuture future = null;
        future = bootstrap.connect(new InetSocketAddress(OtherInfo.SERVER_HOST,OtherInfo.SERVER_PORT));
        future.addListener(channelFutureListener);
    }
}
